<script lang="ts" setup>
import { onBeforeMount, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { getCodeImg, login } from '@/api/login';
import { useRouter } from 'vue-router';

const router = useRouter();
const codeUrl = ref<string>('');
const loginForm = ref({
  username: 'admin',
  password: 'admin123',
  code: '',
  uuid: ''
});

onBeforeMount(() => {
  getCode();
});

const getCode = () => {
  getCodeImg().then(res => {
    const captchaEnabled = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled;
    if (captchaEnabled) {
      codeUrl.value = 'data:image/gif;base64,' + res.data.img;
      loginForm.value.uuid = res.data.uuid;
    }
  });
};

const onLogin = () => {
  login(loginForm.value).then(res => {
    sessionStorage.setItem('app-token', res.data.token);
    ElMessage.success('登录成功');
    router.push('/');
  });
};
</script>

<template>
  <div class="login">
    <el-input v-model="loginForm.username" placeholder="用户名" size="large"></el-input>
    <br />
    <el-input v-model="loginForm.password" placeholder="密码" size="large"></el-input>
    <br />
    <div style="display: flex; align-items: center; width: 100%">
      <el-input v-model="loginForm.code" placeholder="验证码" size="large" @keydown.enter="onLogin"></el-input>
      &nbsp;&nbsp;&nbsp;&nbsp;
      <img :src="codeUrl" alt="" class="login-code-img" @click="getCode" />
    </div>
    <br />
    <el-button size="large" style="width: 100%" type="primary" @click="onLogin">登录</el-button>
  </div>
</template>

<style lang="scss" scoped>
.login {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 400px;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  .login-code-img {
    height: 40px;
  }
}
</style>
